namespace Microsoft.VisualStudio.EnterpriseTools.OperationDesigner
{
    using Microsoft.VisualStudio.EnterpriseTools.ArtifactModel.Clr;
    using Microsoft.VisualStudio.Modeling;
    using System;

    public class FieldValueColumn : ColumnDescriptor
    {
        public FieldValueColumn() : base(ClrBranchStrings.GetString("FieldValueColumnTitle"))
        {
        }

        public override void AddEventHandlers(Store store)
        {
            store.EventManagerDirectory.ElementAttributeChanged.Add(store.MetaDataDirectory.FindMetaAttribute(ClrField.InitialValueMetaAttributeGuid), new ElementAttributeChangedEventHandler(this.OnValueChanged));
        }

        public override object GetValue(object component)
        {
            ClrField field = component as ClrField;
            if (field != null)
            {
                return field.InitialValue;
            }
            return string.Empty;
        }

        public override OperationDesignerValueSupportedStates GetValueSupported(object component)
        {
            if (component is ClrField)
            {
                return OperationDesignerValueSupportedStates.Supported;
            }
            return OperationDesignerValueSupportedStates.Unsupported;
        }

        private void OnValueChanged(object sender, ElementAttributeChangedEventArgs e)
        {
            if (base.Host != null)
            {
                base.Host.Refresh(e.ModelElement);
            }
        }

        public override void RemoveEventHandlers(Store store)
        {
            store.EventManagerDirectory.ElementAttributeChanged.Remove(store.MetaDataDirectory.FindMetaAttribute(ClrField.InitialValueMetaAttributeGuid), new ElementAttributeChangedEventHandler(this.OnValueChanged));
        }

        public override void SetValue(object component, object value)
        {
            ClrField field = component as ClrField;
            if (field != null)
            {
                Transaction transaction = field.Store.TransactionManager.BeginTransaction("CreateFieldUndoText");
                try
                {
                    field.InitialValue = (string) value;
                    transaction.Commit();
                }
                finally
                {
                    if (transaction.IsActive)
                    {
                        transaction.Rollback();
                    }
                }
            }
        }

        public override string Category
        {
            get
            {
                return ClrBranchStrings.GetString("ImplementationCategory");
            }
        }
    }
}

